package com.zxy.ziems.server.alarm.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

//@Component
@Slf4j
public class NettyClient  {
    private EventLoopGroup group = new NioEventLoopGroup();
    @Value("${netty.alarm.port}")
    private int port;
    @Value("${netty.alarm.host}")
    private String host;
    private SocketChannel socketChannel;
    private Bootstrap bootstrap;


    @PostConstruct
    public void init() {
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //加入处理器
                        ch.pipeline().addLast(new ClientHandlerInitilizer(NettyClient.this));
                    }
                });
        connect();
    }
    public void connect() {
        //启动客户端去连接服务器端
        ChannelFuture future = bootstrap.connect(host, port);
        //客户端断线重连逻辑
        future.addListener((ChannelFutureListener) future1 -> {
            if (future1.isSuccess()) {
                log.info("连接Netty服务端成功");
            } else {
                log.info("连接失败，进行断线重连");
                //重连交给后端线程执行
                future.channel().eventLoop().schedule(() -> {
                    log.error("重连服务端...");
                    try {
                        connect();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }, 3000, TimeUnit.MILLISECONDS);
            }
        });
        //对通道关闭进行监听
        future.channel().closeFuture();
    }
}

